package com.zysc.processflow.common.base;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zysc.processflow.common.util.DateTimeUtils;
import com.zysc.processflow.common.util.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

public class BaseService<TMapper extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<TMapper, T> {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * 执行SQL
     * @param sql
     * @return
     */
    public List<Map<String, Object>> excuteQuerySql(String sql){
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        PreparedStatement pst = null;
        //创建数据库连接
        SqlSession session = SqlSessionUtils.getSqlSession(sqlSessionTemplate.getSqlSessionFactory(),
                sqlSessionTemplate.getExecutorType(), sqlSessionTemplate.getPersistenceExceptionTranslator());
        ResultSet result = null;
        try {
            pst = session.getConnection().prepareStatement(sql);
            result = pst.executeQuery();
            ResultSetMetaData md = result.getMetaData(); //获得结果集结构信息,元数据
            int columnCount = md.getColumnCount();   //获得列数
            while (result.next()) {
                Map<String,Object> rowData = new HashMap<String,Object>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), result.getObject(i));
                }
                list.add(rowData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(pst!=null){
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            SqlSessionUtils.closeSqlSession(session, sqlSessionTemplate.getSqlSessionFactory());
        }
        return list;
    }

    @Override
    public boolean saveBatch(Collection<T> entityList) {
        for(T data : entityList){
            if(StringUtils.isNull(data.getId())){
                String uuid = UUID.randomUUID().toString();
                data.setId(uuid);
            }
            Long tm = DateTimeUtils.GetCurrentMillisecond();
            data.setUpdatetime(tm);
            data.setCreatetime(tm);
        }
        return super.saveBatch(entityList);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<T> entityList) {
        for(T data : entityList){
            Long tm = DateTimeUtils.GetCurrentMillisecond();
            data.setUpdatetime(tm);
            if(data.getId() == null || data.getId().equals("")) {
                String uuid = UUID.randomUUID().toString();
                data.setId(uuid);
                data.setCreatetime(tm);
            }
        }
        return super.saveOrUpdateBatch(entityList);
    }

    @Override
    public boolean save(T entity) {
        if(StringUtils.isNull(entity.getId())){
            String uuid = UUID.randomUUID().toString();
            entity.setId(uuid);
        }
        Long tm = DateTimeUtils.GetCurrentMillisecond();
        entity.setUpdatetime(tm);
        entity.setCreatetime(tm);
        return super.save(entity);
    }

    @Override
    public boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper) {
        Long tm = DateTimeUtils.GetCurrentMillisecond();
        entity.setUpdatetime(tm);
        if (entity.getId() == null || entity.getId().equals("")) {
            String uuid = UUID.randomUUID().toString();
            entity.setId(uuid);
            entity.setCreatetime(tm);
        }
        return super.saveOrUpdate(entity, updateWrapper);
    }
}
